//
//  GKZYPostBarDetailsViewController.m
//  GKZYAid
//
//  Created by lanou3g on 16/3/14.
//  Copyright © 2016年 GKZYAid. All rights reserved.
//

#import "GKZYPostBarDetailsViewController.h"

@interface GKZYPostBarDetailsViewController ()

@end

@implementation GKZYPostBarDetailsViewController

//加载数据
- (void)viewWillAppear:(BOOL)animated
{
    self.arrayWithoutPublish = [[NSMutableArray alloc] init];
    self.arrayPublication = [[NSMutableArray alloc] init];
    self.strPublicationID = self.postBar.strPublicationID;
    AVQuery *query = [PostBar query];
    [query whereKey:@"strPublicationID" equalTo:self.strPublicationID];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        self.arrayAllData = objects.mutableCopy;
        for (PostBar *bar in self.arrayAllData) {
            if (bar.strCommentUserName.length || bar.strReplyUserName.length) {
                [self.arrayWithoutPublish addObject:bar];
            }else if(bar.strPublicationUserName.length){
                [self.arrayPublication addObject:bar];
            }
        }
        [self.tableViewDetails reloadData];
    }];
}

//加载视图
- (void)viewDidLoad
{
    self.tableViewDetails = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:(UITableViewStyleGrouped)];
    [self.view addSubview:self.tableViewDetails];
    self.tableViewDetails.delegate = self;
    self.tableViewDetails.dataSource = self;
    self.tableViewDetails.separatorStyle = UITableViewCellSeparatorStyleNone;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
}

//自适应键盘高度
- (void)keyboardWillShow:(NSNotification *)notification
{
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    NSInteger height = keyboardRect.size.height;
    self.keyboardHeight = height;
    
    self.TBView.frame = CGRectMake(0, self.view.frame.size.height * 0.93 - self.keyboardHeight, self.view.frame.size.width, self.view.frame.size.height * 0.07);
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayWithoutPublish.count + 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.postBar.arrayPublicationImage.count) {
        if ((self.postBar.arrayPublicationImage.count - 1) / 3.0 > 0 && (self.postBar.arrayPublicationImage.count - 1) / 3.0 <= 1) {
            self.viewRow = 1;
        }else if ((self.postBar.arrayPublicationImage.count - 1) / 3.0 > 1 && (self.postBar.arrayPublicationImage.count - 1) / 3.0 <= 2){
            self.viewRow = 2;
        }else if ((self.postBar.arrayPublicationImage.count - 1) / 3.0 > 2){
            self.viewRow = 3;
        }
    }
    
    if (indexPath.row == 0) {   //发帖内容详情
        static NSString *detailsCell = @"cellDetails";
        GKZYPostBarDetailsTableViewCell *cellDetails = [tableView dequeueReusableCellWithIdentifier:detailsCell];
        if (!cellDetails) {
            cellDetails = [[GKZYPostBarDetailsTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:detailsCell viewRow:self.viewRow];
        }
        [self changeCellFrameAndContentOnPostBarDetailsTableViewCell:cellDetails];
        return cellDetails;
    }
    if (indexPath.row == 1) {   //点赞评论
        static NSString *likeCell = @"cellLike";
        GKZYPostBarLikeTableViewCell *cellLike = [tableView dequeueReusableCellWithIdentifier:likeCell];
        if (!cellLike) {
            cellLike = [[GKZYPostBarLikeTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:likeCell];
        }
        [self changeCellContentOnPostBarLikeTableViewCell:cellLike];
        return cellLike;
    }
    if (self.arrayWithoutPublish[indexPath.row - 2][@"strCommentUserName"]) {   //评论cell
        static NSString *commentCell = @"cellComment";
        GKZYPostBarCommentTableViewCell *cellComment = [tableView dequeueReusableCellWithIdentifier:commentCell];
        if (!cellComment) {
            cellComment = [[GKZYPostBarCommentTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:commentCell];
        }
        [self changeCellFrameAndContentOnPostBarCommentTableViewCell:cellComment withIndex:indexPath.row - 2];
        return cellComment;
    }
    if (self.arrayWithoutPublish[indexPath.row -2][@"strReplyUserName"]) {      //回复cell
        static NSString *replyCell = @"cellReply";
        GKZYPostBarReplyTableViewCell *cellReply =  [tableView dequeueReusableCellWithIdentifier:replyCell];
        if (!cellReply) {
            cellReply = [[GKZYPostBarReplyTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:replyCell];
        }
        [self changeCellFrameAndContentOnPostBarReplyTableViewCell:cellReply withIndex:indexPath.row - 2];
        return cellReply;
    }
    return nil;
}

//详情cell赋值
- (void)changeCellFrameAndContentOnPostBarDetailsTableViewCell:(GKZYPostBarDetailsTableViewCell *)cellDetails
{
    NSMutableArray *array1 = [[NSMutableArray alloc] initWithObjects:cellDetails.detailsImageView1.imageView1,cellDetails.detailsImageView1.imageView2,cellDetails.detailsImageView1.imageView3, nil];
    NSMutableArray *array2 = [[NSMutableArray alloc] initWithObjects:cellDetails.detailsImageView2.imageView1,cellDetails.detailsImageView2.imageView2,cellDetails.detailsImageView2.imageView3, nil];
    NSMutableArray *array3 = [[NSMutableArray alloc] initWithObjects:cellDetails.detailsImageView3.imageView1,cellDetails.detailsImageView3.imageView2,cellDetails.detailsImageView3.imageView3, nil];
    
    cellDetails.labelUserName.text = self.postBar.strPublicationUserName;
    
    [self addUserIconOnCell:cellDetails];
    
    for (int i = 0; i < self.postBar.arrayPublicationImage.count; i++) {
        if (i != self.postBar.arrayPublicationImage.count - 1) {
            AVFile *fileImage = self.postBar.arrayPublicationImage[i];
            if (i < 3) {
                [(UIImageView *)array1[i] sd_setImageWithURL:[NSURL URLWithString:fileImage.url]];
            }else if (i > 2 && i < 6){
                [(UIImageView *)array2[i - 3] sd_setImageWithURL:[NSURL URLWithString:fileImage.url]];
            }else if (i > 5 && i < 9){
                [(UIImageView *)array3[i - 6] sd_setImageWithURL:[NSURL URLWithString:fileImage.url]];
            }
        }
    }
    cellDetails.labelContent.text = self.postBar.strPublicationrContent;
    CGRect rectDetails = cellDetails.labelContent.frame;
    rectDetails.size.height = [cellDetails labelHeight:self.postBar.strPublicationrContent withFont:17.0f] + 30;
    cellDetails.labelContent.frame = rectDetails;
    
    CGRect rectCellDetails = cellDetails.frame;
    rectCellDetails.size.height = self.view.frame.size.width * 0.35 + [cellDetails labelHeight:self.postBar.strPublicationrContent withFont:17.0f] + [cellDetails viewImageHeight] ;
    cellDetails.frame = rectCellDetails;
    self.cellPublicationHeight = cellDetails.frame.size.height;
}

//添加用户头像
- (void)addUserIconOnCell:(GKZYPostBarDetailsTableViewCell *)cellDetails
{
    AVQuery *query = [AVQuery queryWithClassName:@"UserInformation"];
    [query whereKey:@"userName" equalTo:self.postBar.strPublicationUserName];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        AVFile *fileUserIcon = objects.firstObject[@"userImage"];
        [cellDetails.imageUserHeader sd_setImageWithURL:[NSURL URLWithString:fileUserIcon.url]];
    }];
}

//评论cell赋值
- (void)changeCellFrameAndContentOnPostBarCommentTableViewCell:(GKZYPostBarCommentTableViewCell *)cellComment withIndex:(NSInteger)index
{
    NSString *strUserName = self.arrayWithoutPublish[index][@"strCommentUserName"];
    self.strCommentUserName = strUserName;
    NSString *strComment = self.arrayWithoutPublish[index][@"strCommentContent"];
    NSString *strConnent = [NSString stringWithFormat:@"%@:%@",strUserName,strComment];
    
    //设置cell高度
    CGRect rectComment = cellComment.frame;
    rectComment.size.height = [cellComment labelHeight:strConnent withFont:17.0f];
    cellComment.frame = rectComment;
    self.cellCommentHeight = cellComment.frame.size.height + self.view.frame.size.width * 0.03 + 30;
    self.cellHeight = self.cellCommentHeight;
    cellComment.color = [UIColor blueColor];
    cellComment.strLabelContent = strConnent;
    
    [cellComment.buttonSkip addTarget:self action:@selector(buttonSkipAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [cellComment.buttonReply addTarget:self action:@selector(buttonReplyAction:) forControlEvents:(UIControlEventTouchUpInside)];
}

//回复cell赋值
- (void)changeCellFrameAndContentOnPostBarReplyTableViewCell:(GKZYPostBarReplyTableViewCell *)cellReply withIndex:(NSInteger)index
{
    NSString *strReplyUserName = self.arrayWithoutPublish[index][@"strReplyUserName"];
    NSString *strPassivityReplyUserName = self.strCommentUserName;
    NSString *strContent = self.arrayWithoutPublish[index][@"strReplyContent"];
    NSString *strContentAll = [NSString stringWithFormat:@"%@回复%@:\n%@",strReplyUserName,strPassivityReplyUserName,strContent];
    
    CGRect rectReply = cellReply.frame;
    rectReply.size.height = [cellReply labelHeight:strContentAll withFont:17.0f];
    cellReply.frame = rectReply;
    self.cellReplyHeight = cellReply.frame.size.height + self.view.frame.size.width * 0.03 + 30;
    self.cellHeight = self.cellReplyHeight;
    cellReply.color = [UIColor blueColor];
    cellReply.strReplyUserName = strReplyUserName;
    cellReply.strPassivityReplyUserName = strPassivityReplyUserName;
    cellReply.strLabelContent = strContentAll;
}

//评论,喜欢cell事件
- (void)changeCellContentOnPostBarLikeTableViewCell:(GKZYPostBarLikeTableViewCell *)cellLike
{
    [cellLike.likeView.buttonLike setImage:[UIImage imageNamed:@"like"] forState:(UIControlStateNormal)];
    for (NSString *strUserName in self.postBar.arrayUserLike) {
        if ([strUserName isEqualToString:[AVUser currentUser].username]) {
            [cellLike.likeView.buttonLike setImage:[UIImage imageNamed:@"isliked"] forState:(UIControlStateNormal)];
        }
    }
    [cellLike.likeView.buttonComment addTarget:self action:@selector(buttonCommentAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [cellLike.likeView.buttonLike addTarget:self action:@selector(buttonLikeAction:) forControlEvents:(UIControlEventTouchUpInside)];
    cellLike.likeView.labelCommentCount.text = [NSString stringWithFormat:@"%ld",self.arrayWithoutPublish.count];
    cellLike.likeView.labelLikeCount.text = [NSString stringWithFormat:@"%ld",self.postBar.arrayUserLike.count];
}

//评论按钮
- (void)buttonCommentAction:(UIButton *)sender
{
    if ([AVUser currentUser].username) {
        self.TBView = [[TextViewButtonView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height * 0.93 - self.keyboardHeight, self.view.frame.size.width, self.view.frame.size.height * 0.07)];
        [self.TBView.buttonComment setTitle:@"评论" forState:(UIControlStateNormal)];
        [self.view addSubview:self.TBView];
        [self.TBView.textViewInput becomeFirstResponder];
        [self.TBView.buttonComment addTarget:self action:@selector(TBButtonCommentAction:) forControlEvents:(UIControlEventTouchUpInside)];
    }else{
        GKZYUserLoginViewController *loginVC = [[GKZYUserLoginViewController alloc] init];
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}

//评论事件
- (void)TBButtonCommentAction:(UIButton *)sender
{
    [self.TBView removeFromSuperview];
    [self.TBView.textViewInput resignFirstResponder];
    PostBar *bar = [[PostBar alloc] init];
    bar.strPublicationID = self.strPublicationID;
    bar.strCommentUserName = [AVUser currentUser].username;
    bar.strCommentContent = self.TBView.textViewInput.text;
    [self.arrayWithoutPublish addObject:bar];
    [bar saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            NSLog(@"保存成功");
        }else{
            NSLog(@"%@",error);
        }
    }];
    [self.tableViewDetails reloadData];
}

//跳转事件
- (void)buttonSkipAction:(UIButton *)sender
{
#warning ----- buttonSkipAction will skip to UserHomePage (添加手势,跳转到用户首页)
    NSLog(@"buttonSkip");
}

//回复按钮
- (void)buttonReplyAction:(UIButton *)sender
{
    if ([AVUser currentUser].username) {
        self.TBView = [[TextViewButtonView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height * 0.93 - self.keyboardHeight, self.view.frame.size.width, self.view.frame.size.height * 0.07)];
        [self.TBView.buttonComment setTitle:@"回复" forState:(UIControlStateNormal)];
        [self.view addSubview:self.TBView];
        [self.TBView.textViewInput becomeFirstResponder];
        [self.TBView.buttonComment addTarget:self action:@selector(TBButtonReplyAction:) forControlEvents:(UIControlEventTouchUpInside)];
    }else{
        GKZYUserLoginViewController *loginVC = [[GKZYUserLoginViewController alloc] init];
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}

//回复事件
- (void)TBButtonReplyAction:(UIButton *)sender
{
    if (![self.strCommentUserName isEqualToString:[AVUser currentUser].username]) {
        [self.TBView removeFromSuperview];
        [self.TBView.textViewInput resignFirstResponder];
        PostBar *bar = [[PostBar alloc] init];
        bar.strPublicationID = self.strPublicationID;
        bar.strReplyUserName = [AVUser currentUser].username;
        bar.strReplyContent = self.TBView.textViewInput.text;
        bar.strPassivityReplyUserName = self.strCommentUserName;
        [self.arrayWithoutPublish addObject:bar];
        [bar saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                NSLog(@"保存成功");
            }else{
                NSLog(@"%@",error);
            }
        }];
        [self.tableViewDetails reloadData];
    }else{
        [self addReplyUserWrongErrorAlertController];
    }
}

//评论人与回复人相同
- (void)addReplyUserWrongErrorAlertController
{
    [self.TBView removeFromSuperview];
    [self.TBView.textViewInput resignFirstResponder];
    UIAlertController *controller = [UIAlertController alertControllerWithTitle:@"回复人与评论人不能相同" message:@"" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil];
    [controller addAction:action];
    [self presentViewController:controller animated:YES completion:nil];
}

- (void)buttonLikeAction:(UIButton *)sender
{
    if ([AVUser currentUser].username) {
        for (NSString *userLike in self.postBar.arrayUserLike) {
            if ([userLike isEqualToString:[AVUser currentUser].username]) {
                [(NSMutableArray *)self.postBar.arrayUserLike removeObject:userLike];
                [self.postBar setObject:self.postBar.arrayUserLike forKey:@"arrayUserLike"];
                [sender setImage:[UIImage imageNamed:@"like"] forState:(UIControlStateNormal)];
                [self.postBar saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                    if (succeeded) {
                        [self.tableViewDetails reloadData];
                        NSLog(@"保存成功");
                    }else{
                        NSLog(@"%@",error);
                    }
                }];
            }
            return;
        }
        [(NSMutableArray *)self.postBar.arrayUserLike addObject:[AVUser currentUser].username];
        [self.postBar setObject:self.postBar.arrayUserLike forKey:@"arrayUserLike"];
        [sender setImage:[UIImage imageNamed:@"isliked"] forState:(UIControlStateNormal)];
        [self.postBar saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                [self.tableViewDetails reloadData];
                NSLog(@"保存成功");
            }else{
                NSLog(@"%@",error);
            }
        }];
    }else{
        GKZYUserLoginViewController *loginVC = [[GKZYUserLoginViewController alloc] init];
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//cell点击事件,进入查看图片页面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0 && ((NSMutableArray *)self.arrayPublication.firstObject[@"arrayPublicationImage"]).count > 0) {
        GKZYPostBarImageViewController *postBarImageVC = [[GKZYPostBarImageViewController alloc] init];
        postBarImageVC.strPublicationID = self.strPublicationID;
        [self.navigationController pushViewController:postBarImageVC animated:YES];
    }
}

//返回cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return self.cellPublicationHeight;
    }else if (indexPath.row == 1){
        return self.view.frame.size.width * 0.1;
    }else{
        return self.cellHeight + 30;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
